import {
	getCartList,
	delCartList
} from '@/api'

export default {
	state: {
		list: [
		// {
		// 		checked: false,
		// 		id: 11,
		// 		title: "商品标题111",
		// 		cover: "/static/images/demo/list/1.jpg",
		// 		pprice: 200,
		// 		num: 1,
		// 		minnum: 1,
		// 		maxnum: 10
		// 	},
		// 	{
		// 		checked: false,
		// 		id: 12,
		// 		title: "商品标题222",
		// 		cover: "/static/images/demo/list/2.jpg",
		// 		pprice: 100,
		// 		num: 2,
		// 		minnum: 1,
		// 		maxnum: 10
		// 	},
		// 	{
		// 		checked: false,
		// 		id: 13,
		// 		title: "商品标题333",
		// 		cover: "/static/images/demo/list/3.jpg",
		// 		pprice: 300,
		// 		num: 1,
		// 		minnum: 1,
		// 		maxnum: 10
		// 	}
		],
		selectedAll: [] // 修正属性名
	},
	getters: {
		checkedAll(state) {
			return state.list.length === state.selectedAll.length && state.list.every(item => item.checked);
			// 添加了对每个 item.checked 的检查，以确保所有项都被选中
		},
		totalPrice(state) {
			let total = 0;
			state.list.forEach(item => {
				if (item.checked) {
					total += item.num * item.pprice
				}
			})
			return total;
		}
	},
	mutations: {
		selectItem(state, index) {
			let id = state.list[index].id;
			let i = state.selectedAll.indexOf(id);
			if (i > -1) {
				state.list[index].checked = false; // 修正属性名
				state.selectedAll.splice(i, 1);
			} else {
				state.list[index].checked = true; // 修正属性名
				state.selectedAll.push(id);
			}
		},
		selectAll(state) {
			state.list.forEach(item => {
				item.checked = true;
				if (!state.selectedAll.includes(item.id)) { // 避免重复添加
					state.selectedAll.push(item.id);
				}
			});
		},
		unSelectAll(state) {
			state.list.forEach(item => {
				item.checked = false;
			});
			state.selectedAll = []; // 只在循环外设置一次空数组
		},
		delGoods(state) {
			uni.showModal({
				title: '提示',
				content: '您确定要删除吗',
				success: function(res) {
					if (res.confirm) {
						state.list = state.list.filter(item => {
							return !item.checked
						})
						state.selectAll = []
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}
	},
	actions: {
		doSelectAll({
			getters,
			commit
		}) {
			getters.checkedAll ? commit('unSelectAll') : commit('selectAll');
		}
	}
}